<?php
/**
 * Created by PhpStorm.
 * User: ASUS
 * Date: 2019-10-17
 * Time: 18:00
 */

namespace App\Extensions\Log\V1;

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;

class InstanceLog
{
    private static $monologInstances = [];

    /**
     * @param string $name
     * @return Logger
     */
    public static function instance(string $name = null)
    {
        if (empty($name)) {
            return app('log');
        }

        if (!array_key_exists($name, static::$monologInstances)) {
            static::$monologInstances[$name] = new Logger($name);

            // 设置日志处理手柄，默认为写入文件（还有mail、console、db、redis等方式，详见Monolog\handler 目录）
            //TODO 日志存留天数可设置
            $handler = new RotatingFileHandler(storage_path('logs/' . $name) . '.log', 0);
            $handler->setFormatter(new LineFormatter(null, null, true, true));

            static::$monologInstances[$name]->pushHandler($handler);
        }

        return static::$monologInstances[$name];
    }
}
